import update from './atom/db/update';
import query from './atom/db/query';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	rowdata: { _id: string; teacher_no: string; }
}

async function atom(msg: Message) {
	const systemid = '5981';

	const q = query(action_id, session_id, spaceid, systemid);
	q.prepare('usable_exam_teacher', ['_id', 'teacher_no'], { teacher_no: msg.rowdata.teacher_no }, 0, 1);
	const t = await q.exec();
	if (t[0].length === 0) {
		const { prepare, exec } = update(action_id, session_id, spaceid, systemid);
		prepare('usable_exam_teacher', [msg.rowdata]);
		const ret = await exec();
		if (ret.code === 1) {
			return 'success';
		} else {
			return 'fail';
		}
	} else if (t[0].length === 1) {
		if (msg.rowdata._id === t[0][0]._id) {
			const { prepare, exec } = update(action_id, session_id, spaceid, systemid);
			prepare('usable_exam_teacher', [msg.rowdata]);
			const ret = await exec();
			if (ret.code === 1) {
				return 'success';
			} else {
				return 'fail';
			}
		} else {
			return 'fail:repeat';
		}
	} else {
		return 'failrepeat';
	}



}
